package ClientLibrary.UI;

import ClientLibrary.Board;
import ClientLibrary.Network.NetLayer;
import CommonLibrary.Commnads.CreateGameRequest;
import CommonLibrary.Commnads.JoinGameRequest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MListener implements MouseListener {
    
    private NetLayer netLayer;
    MenuForm menuForm;
    
    public MListener(NetLayer l, MenuForm f){
        this.netLayer = l;
        this.menuForm = f;
    }
    
    @Override
    public void mouseClicked(MouseEvent e) {          
        Object obj = ((JList)e.getComponent()).getSelectedValue();
        String s = obj.toString();
        
        if(s.split(" - ").length == 2)
        {
            String name = s.split(" - ")[0];

            if(s.split(" - ")[1] == "black")
            {
                Board.getBoard().setSide(1);
            }
            else
            {
                Board.getBoard().setSide(0);
            }

            Board.getBoard().setGameId(MenuForm.getCurrentForm().getGameId(name));
            JoinGameRequest joinRequest = new JoinGameRequest(MenuForm.getCurrentForm().getGameId(name), Board.getBoard().getPlayerId());
            try
            {
                this.netLayer.sendCommand(joinRequest);
            }
            catch (Exception error)
            {
                // TODO
            }
        }
        else
        {
            try
            {
                CreateGameRequest createGame = new CreateGameRequest();
                createGame.setPlayerID(Board.getBoard().getPlayerId());

                createGame.setSide(s == "New Game(White)" ? 1 : 0);
                Board.getBoard().setSide(s == "New Game(White)" ? 1 : 0);
                this.netLayer.sendCommand(createGame);
            }
            catch (Exception error)
            {
                System.out.print("Can't send a CreateGameRequest");
            }
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void mouseExited(MouseEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
